#!/bin/bash
#
### BEGIN INIT INFO
# Provides: cuttlefish-host_orchestrator
# Required-Start: $network $remote_fs
# Required-Stop: $network $remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Cuttlefish Host Orchestrator service
# Description: The Host Orchestrator service provides the signaling
#              server used by all cuttlefish instances running in this
#              host as well as orchestration capabilities.
### END INIT INFO
#
# Copyright (C) 2021 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Make sure calls to this script get redirected to systemctl when
# using systemd

. /lib/lsb/init-functions

if [ -f /etc/default/cuttlefish-host_orchestrator ]; then
    . /etc/default/cuttlefish-host_orchestrator
fi

orchestrator_cvd_artifacts_dir=${orchestrator_cvd_artifacts_dir:-"/var/lib/cuttlefish-common"}

# Run as the configured user or root if none was specified
orchestrator_user="${orchestrator_user:-root}"

RUN_DIR="/run/cuttlefish"
ORCHESTRATOR_BIN="/usr/lib/cuttlefish-common/bin/host_orchestrator"
ORCHESTRATOR_PIDFILE="${RUN_DIR}"/host_orchestrator.pid
ASSET_DIR="/usr/share/cuttlefish-common/operator"

set_config_expr() {
  echo "\${$2+"export $1=\$$2"}"
}

prepare_run_dir() {
  mkdir -p "${RUN_DIR}"
  chown "${orchestrator_user}":cvdnetwork "${RUN_DIR}"
  chmod 775 "${RUN_DIR}"
}

start_orchestrator() {
  mkdir -p  "${orchestrator_cvd_artifacts_dir}"
  chown "${orchestrator_user}":cvdnetwork "${orchestrator_cvd_artifacts_dir}"

  args=()

  if [[ -n "${orchestrator_http_port}" ]]; then
    args+=("--http_port=${orchestrator_http_port}")
  fi
  if [[ -n "${orchestrator_android_build_url}" ]]; then
    args+=("--android_build_url=${orchestrator_android_build_url}")
  fi
  if [[ -n "${orchestrator_cvd_artifacts_dir}" ]]; then
    args+=("--cvd_artifacts_dir=${orchestrator_cvd_artifacts_dir}")
  fi
  if [[ -n "${orchestrator_cvd_creation_timeout_secs}" ]]; then
    args+=("--cvd_creation_timeout_secs=${orchestrator_cvd_creation_timeout_secs}")
  fi
  if [[ -n "${operator_http_port}" ]]; then
    args+=("--operator_http_port=${operator_http_port}")
  fi
  if [[ -n "${orchestrator_listen_address}" ]]; then
    args+=("--listen_addr=${orchestrator_listen_address}")
  fi
  if [[ -n "${orchestrator_cvd_user}" ]]; then
    args+=("--cvd_user=${orchestrator_cvd_user}")
  fi

  start-stop-daemon --start \
    --pidfile "${ORCHESTRATOR_PIDFILE}" \
    --chuid "${orchestrator_user}":cvdnetwork \
    --chdir "${ASSET_DIR}" \
    --background --no-close \
    --make-pidfile \
    --exec "${ORCHESTRATOR_BIN}" -- "${args[@]}"
}

start() {
  prepare_run_dir

  start_orchestrator
}

stop() {
  start-stop-daemon --stop \
    --pidfile "${ORCHESTRATOR_PIDFILE}" \
    --remove-pidfile \
    --exec "${ORCHESTRATOR_BIN}"
}

status() {
  # Return
  #   0 if daemon is running
  #   1 if daemon is dead and pid file exists
  #   3 if daemon is not running
  #   4 if daemon status is unknown
  start-stop-daemon --start --quiet --pidfile "${ORCHESTRATOR_PIDFILE}" --exec ${ORCHESTRATOR_BIN} --test > /dev/null
  case "${?}" in
    0) [ -e "${ORCHESTRATOR_PIDFILE}" ] && return 1 ; return 3 ;;
    1) return 0 ;;
    *) return 4 ;;
  esac
}

usage() {
    echo $0: start\|stop\|status
}

if test $# != 1; then
    usage
else
    case "$1" in
        --help)
            usage 0
            ;;
        start|stop|status)
            "$1"
            ;;
        restart|force-reload|condrestart|try-restart)
            stop && start
            ;;
        reload)
            # Nothing to do
            ;;
        shutdown)
            stop
            ;;
        *)
            usage
            ;;
    esac
fi
exit 0
